import React, { Component, PropTypes } from 'react';
import { InputNumber } from 'antd'

class FormulaField extends Component {

  state = {
    value: undefined
  };

  lastFormulaValue = undefined;

  onChange = value => {
    this.setState({ value }, this.dispatchOnChange)
  };

  componentDidMount() {
    const { form, formula, value } = this.props;
    if (formula && form) {
      this.setState({ value });
    }
  };

  componentWillReceiveProps(nextProps) {
    const { form, formula, readFormula, fields } = nextProps;
    if(formula && form) {
      if(nextProps.value !== this.props.value) {
        this.setState({ value: nextProps.value });
      } else {
        const { value } = this.state;
        let nextFormulaValue = readFormula(formula, form, value, fields);
        if(this.lastFormulaValue !== nextFormulaValue) {
          this.setState({ value: nextFormulaValue }, this.dispatchOnChange);
          this.lastFormulaValue = nextFormulaValue;
        }
      }
    }
  }

  dispatchOnChange = () => {
    const { value } = this.state;
    const { onChange, max, precision } = this.props;
    onChange && onChange(value > max ? max.toFixed(precision) : Number(value).toFixed(precision));
  };

  render() {
    const { value } = this.state;
    const { disabled, precision, min, max, step, placeholder, style, className, promptInfo } = this.props;
    const inputProps = {
      disabled, precision, min, max, step, placeholder, style, className
    };
    return (
      <div>
        <InputNumber
          onChange={this.onChange}
          value={value}
          {...inputProps}
        />
        <div>{promptInfo}</div>
      </div>
    );
  }

  static propTypes = {
    readFormula: PropTypes.func
  };

  static defaultProps = {
    readFormula: (formula, form, source, fields) => {
      let valid = true;
      let target = formula.replace(/\{(\S*?)\}/g, (target, $1) => {
        let value = form.getFieldValue($1);
        valid = valid && !isNaN(value);
        return value;
      });
      target = target.replace(/×/g, '*');
      target = target.replace(/÷/g, '/');
      return valid ? eval(target) : source;
    },
    max: Number.MAX_SAFE_INTEGER,
    min: -Number.MAX_SAFE_INTEGER,
    disabled: false,
    step: 1,
    precision: 0,
    placeholder: '',
    promptInfo: '',
    style: {},
    className: ''
  };

}

export default FormulaField;
